"""
@Project:p8_syl_flask
@File:course.py
@Author:郑凯乐
@Date:10:57
"""
import json
import random
import traceback
from datetime import datetime
import requests,string
from flask import Blueprint,Response,jsonify
from flask_restful import Api,Resource,reqparse,marshal
from common.models import db,rds
from common.models.course import *
from common.models.user import *
from common.model_fields.user_fields import user_fields
from celery_tasks.tasks import phone_code
from sqlalchemy import or_
from captcha.image import ImageCaptcha
from common.model_fields.course import *
from common.utils.jwt_utils import verify_jwt
course_bp = Blueprint("course_bp",__name__,url_prefix='/course')
api = Api(course_bp)

#  标签
class TagsResource(Resource):
    def get(self):
        """获取全部标签"""
        try:
            tags = CourseTag.query.all()
            data = marshal(tags,tag_fields)
            return jsonify(mesage="标签获取成功", data=data)
        except Exception as e:
            print(e)
            return jsonify(message="标签获取失败",code=500)
# 获取课程
class CourseResource(Resource):
    # 获取全部课程
    def get(self):
        try:
            parser = reqparse.RequestParser()
            parser = parser.add_argument('tag_id')
            parser = parser.add_argument('free')
            parser = parser.add_argument('online')
            parser = parser.add_argument('sort')
            args = parser.parse_args()
            tag_id = args.get('tag_id')
            course_types = args.get('free')
            course_sort = args.get("sort")
            course_oline = args.get("online")
            print("tag_id的值%s, course_types的值%s, course_sort的值%s,course_oline的值%s"%(tag_id, course_types, course_sort, course_oline))

            # 获取全部数据
            course_and_tag = CourseandTag.query.all()
            if tag_id  != None:
                course_and_tag = CourseandTag.query.filter_by(tag_id=int(tag_id)).all()

            course_list = []
            for i in course_and_tag:
                course =Course.query.filter_by(id=i.course_id).first()

                """把不满足条件的跳过"""
                # 判断类型
                if course_types != None:
                    if course_types != course.course_type:
                        continue
                #判断是否上线
                if course_oline != None:
                    if int(course_oline) != course.course_status:
                        continue
                course_data = marshal(course,course_fields)
                course_list.append(course_data)
            # 销量
            if course_sort != None:
                temp = self.order_data(course_sort,course_list)

            return jsonify(message = "获取课程成功",code=200,data=course_list)


        except Exception as e:
            print(e)
            return jsonify(message = "获取课程失败",code=500)

    @staticmethod
    def order_data(course_sort, data):
        if int(course_sort) == 1:  # 最新
            for i in range(1, len(data)):
                for j in range(0, len(data) - i):
                    if data[j].get("course_time") < data[j + 1].get("course_time"):
                        queryset_data = data[j]
                        data[j] = data[j + 1]
                        data[j + 1] = queryset_data
        else:  # 学习人数
            for i in range(1, len(data)):
                for j in range(0, len(data) - i):
                    if data[j].get("learner") < data[j + 1].get("learner"):
                        queryset_data = data[j]
                        data[j] = data[j + 1]
                        data[j + 1] = queryset_data
        return data

# 课程详情
class CourseInfoResource(Resource):

    def get(self):
        try:
            parser = reqparse.RequestParser()
            parser.add_argument('cid')
            args = parser.parse_args()
            #根据cid获取课程
            cid = args.get("cid")
            print('cid>>>', cid)
            course = Course.query.filter_by(id=cid).first()
            datas = marshal(course, course_fields)
            print('获取课程成功>', datas)
            # 根据课程获取章节信息
            chapter = Chapters.query.filter_by(course=course.id).all()
            chapter_list = marshal(chapter,chapter_fields)
            #TODO
            # # 章节的字典
            # chapters_dict = json.loads(json.dumps(chapter_list))
            # # 根据章节获取章节下的小节
            # print("章节信息",chapters_dict)
            # for i in chapters_dict:
            #     #根据章节id获取小节
            #     Sections.query.filter_by(chapters=i[id]).all()
            #     #序列化

            print('获取课程下的章节成功', chapter_list)
            return jsonify(message="加载成功", data=datas,section=chapter_list)


        except Exception as e:
            print(e)
            return jsonify(message="获取课程失败", code=500)

class CourseAttation(Resource):
    def put(self):
        """更新课程的关注状态"""
        parser = reqparse.RequestParser()
        parser.add_argument('token')
        parser.add_argument('cid')
        parser.add_argument('is_attention')
        args = parser.parse_args()
        cid = args.get("cid")
        token = args.get("token")
        is_attention = args.get("is_attention")
        print('前端传来token的值是',token,cid,is_attention)
        if token:
            try:
                #校验token
                payload = verify_jwt(token)
            except Exception as e:
                return jsonify(message = "先登录",code=401)
            #获取用户id
            # user_id = payload['user_id']
            try:
                couser = Course.query.filter_by(id=cid).first()
                if is_attention == 0:
                    #取消关注
                    Course.query.filter_by(id=cid).update({"is_attention":0,"attention":couser.attention-1})
                    db.session.commit()
                    return jsonify(message="取消关注成功",code=200)
                else:
                    Course.query.filter_by(id=cid).update({"is_attention": 0, "attention": couser.attention - 1})
                    db.session.commit()
                    return jsonify(message="添加关注成功", code=200)

            except Exception as e:
                return jsonify(message="服务端错误",code=500)

class CourseLearntatus(Resource):
    def get(self):
        """获取用户学习进度"""
        parser = reqparse.RequestParser()
        parser.add_argument('token')
        parser.add_argument('cid')
        args = parser.parse_args()
        cid = args.get("cid")
        token = args.get("token")
        if token:
            try:
                #校验token
                payload = verify_jwt(token)
            except Exception as e:
                return jsonify(message = "先登录",code=401)
            #获取用户id
            user_id = payload['user_id']
        # 获取 课程下的章节
        course_chapters = Course.query.filter_by(course=cid).all()
        #序列化输出
        return  marshal(course_chapters,chapter_fields)


api.add_resource(TagsResource,'/get_tag')
api.add_resource(CourseResource,'/get_course')
api.add_resource(CourseInfoResource, '/courseinfo')
api.add_resource(CourseAttation, '/attation')
api.add_resource(CourseLearntatus, '/learninfo')
